<template>
  <span id="upload-span">
    <el-upload
      class="upload-demo"
      :on-change="onProgress"
      action
      :http-request="uploadFile"
      :before-remove="removeFile"
      :show-file-list="showFileList"
      :limit="limit"
      :file-list="fileList"
      list-type="list"
    >
      <div class="images-item">
        <div class="upload-btn">
          <i>点击上传</i>
        </div>
      </div>
    </el-upload>
    <el-progress :percentage="percentage" v-if="showProgress"></el-progress>
    <el-dialog
      title="图片剪裁"
      :visible.sync="dialogVisibleCropper"
      append-to-body
    >
      <div class="cropper-content">
        <div class="cropper" style="text-align: center">
          <vueCropper
            ref="cropper"
            :img="option.img"
            :outputSize="option.size"
            :outputType="option.outputType"
            :info="true"
            :full="option.full"
            :canMove="option.canMove"
            :canMoveBox="option.canMoveBox"
            :original="option.original"
            :autoCrop="option.autoCrop"
            :fixed="option.fixed"
            :fixedNumber="option.fixedNumber"
            :centerBox="option.centerBox"
            :infoTrue="option.infoTrue"
            :fixedBox="option.fixedBox"
          ></vueCropper>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleCropper = false">取 消</el-button>
        <el-button type="primary" @click="finish" :loading="loading"
          >确认</el-button
        >
      </div>
    </el-dialog>
  </span>
</template>
<script>
import { multiUpload } from "@/utils/upload";
import { parse } from "path-to-regexp";
export default {
  name: "UploadFile",
  props: {
    isCrop: {
      type: Boolean,
      default: false,
    },
    dotTestExtName: {
      type: Boolean,
      default: false,
    },
    limit: {
      type: Number,
      default: 1,
    },
    type: {
      type: String,
      default: "",
    },
    showFileList: {
      type: Boolean,
      default: true,
    },
    fileList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    fileExName: {
      type: Array,
      default: () => {
        return ["jpg", "png", "mp3", "mp4"];
      },
    },
    multipartUpload: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      dialogVisibleCropper: false,
      loadingObj: null,
      percentage: 0,
      showProgress: false,
      loading: false,
      option: {
        img: "", // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 0.8, // 裁剪生成图片的质量
        outputType: "jpeg", // 裁剪生成图片的格式
        canScale: false, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        // autoCropWidth: 300, // 默认生成截图框宽度
        // autoCropHeight: 200, // 默认生成截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [5, 5], // 截图框的宽高比例
        full: true, // 是否输出原图比例的截图
        canMoveBox: true, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: true, // 截图框是否被限制在图片里面
        infoTrue: true, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },
    };
  },
  watch: {
    showProgress(val) {
      if (!val) {
        this.percentage = 0;
      }
    },
  },
  methods: {
    removeFile(file, fileList) {
      this.$emit("uploadSuc", { type: this.type, url: "", file, fileList });
      this.showProgress = false;
    },
    onProgress(file, fileList) {
      // this.loadingObj = this.$loading({
      //   lock: true,
      //   text: "Loading",
      //   spinner: "el-icon-loading",
      //   background: "rgba(0, 0, 0, 0.7)",
      // });
    },
    mUpload(file, exName) {
      multiUpload(
        file.file.uid + "." + exName,
        file.file,
        (success, result) => {
          console.log(result);
          let resUrl = result.res.requestUrls[0].split(result.name)[0];
          let requestProtocol = resUrl.split("://")[0];
          let requestBaseUrl = resUrl.split("://")[1];
          // let url = `${requestProtocol}://${result.bucket}.${requestBaseUrl}${result.name}`;
          let url = `${requestProtocol}://${requestBaseUrl}${result.name}`;
          // 计算长度
          let createEle = document.createElement(this.type);
          createEle.setAttribute("src", url);
          createEle.setAttribute("id", "eleId");
          createEle.style.display = "none";
          let uploadWrap = document.getElementById("upload-span");
          uploadWrap.appendChild(createEle);
          let ele = document.getElementById("eleId");
          ele.onloadedmetadata = () => {
            console.log("metadata loaded!");
            console.log(ele.duration); //打印时长
            this.$emit("uploadSuc", {
              type: this.type,
              url,
              duration: parseInt(ele.duration * 1000),
              fileType: exName,
            });
            uploadWrap.removeChild(createEle);
          };
        },
        {
          progress: (p) => {
            //获取进度条的值
            console.log(p);
            this.percentage = p * 100;
          },
        }
      );
    },
    finish() {
      this.$refs.cropper.getCropBlob((data) => {
        console.log(data);
        this.loading = true;
        this.showProgress = false;
        const tmpCnt = this.fileInfo.file.name.lastIndexOf(".");
        const exName = this.fileInfo.file.name.substring(tmpCnt + 1);
        this.$upload(
          this.fileInfo.file.uid + "." + exName,
          data,
          (success, result) => {
            this.loading = false;
            this.dialogVisibleCropper = false;
            this.$emit("uploadSuc", {
              url: result.url,
            });
          }
        );
      });
    },
    uploadFile(file) {
      this.showProgress = true;
      console.log(file);
      const tmpCnt = file.file.name.lastIndexOf(".");
      const exName = file.file.name.substring(tmpCnt + 1);
      const names = this.fileExName;
      if (!this.dotTestExtName) {
        if (names.indexOf(exName) < 0) {
          this.$message.error("不支持的格式!");
          return;
        }
      }
      if (this.isCrop) {
        this.$nextTick(() => {
          try {
            this.option.img = window.URL.createObjectURL(file.file);
          } catch (error) {
            this.option.img = file.file;
          }
          this.fileInfo = file;
          this.dialogVisibleCropper = true;
        });
        return;
      }
      if (this.multipartUpload) {
        this.mUpload(file, exName);
      } else {
        this.showProgress = false;
        this.$upload(
          file.file.uid + "." + exName,
          file.file,
          (success, result) => {
            this.$emit("uploadSuc", {
              url: result.url,
            });
          }
        );
      }
    },
  },
};
</script>
<style scoped lang="scss">
#videoEle {
  display: none;
}
#audioEle {
  display: none;
}
.cropper-content {
  .cropper {
    width: auto;
    height: 300px;
  }
}
</style>